package com.chengcang.api.modules.busi.controller;

import com.chengcang.api.common.annotation.Login;
import com.chengcang.api.common.utils.DicTransLateUtil;
import com.chengcang.api.modules.busi.dto.BusiInvoiceHeadDTO;
import com.chengcang.api.modules.busi.service.BusiInvoiceHeadService;
import com.chengcang.api.modules.login.utils.UserHolder;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.page.PageData;
import com.chengcang.common.utils.Result;
import com.chengcang.common.validator.ValidatorUtils;
import com.chengcang.common.validator.group.AddGroup;
import com.chengcang.common.validator.group.DefaultGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/invoicehead")
@Api(tags = "发票设置")
public class ApiInvoiceHeadController {

    @Autowired
    private BusiInvoiceHeadService busiInvoiceHeadService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
    @Login
    public Result<PageData<BusiInvoiceHeadDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<BusiInvoiceHeadDTO> page = busiInvoiceHeadService.page(params);
        //dictProcess(page);
        //设置字典转换
        return new Result<PageData<BusiInvoiceHeadDTO>>().ok(page);
    }

    protected void dictProcess(PageData<BusiInvoiceHeadDTO> page) {
        //字典处理
        for (BusiInvoiceHeadDTO dto : page.getList()) {
            try {
                BeanUtils.copyProperties(DicTransLateUtil.translate(dto, true, BusiInvoiceHeadDTO.class), dto);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new CustomException("字典转换异常！");
            }
        }
    }

    @PostMapping
    @ApiOperation("新增发票")
    @Login
    public Result save(@RequestBody BusiInvoiceHeadDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        //补充日期、创建人
        dto.setCreateDate(new Date());
        dto.setUpdateDate(new Date());
        dto.setCreator(UserHolder.getUserId());
        dto.setUpdater(UserHolder.getUserId());
        dto.setTenantId(UserHolder.getUser().getDefaultTenantId());
        //新增设置为默认发票
        if (0 == dto.getDefaulted()){
            //修改原默认发票为非默认
            busiInvoiceHeadService.updateOldDefault();
        }
        busiInvoiceHeadService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @Login
    public Result update(@RequestBody BusiInvoiceHeadDTO dto) {
        if (!Pattern.matches("^[a-zA-Z0-9]{1,20}$",dto.getInvoiceCode())){
            throw new CustomException("企业税号格式错误");
        }
        busiInvoiceHeadService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @Login
    public Result delete(@RequestParam Long id) {
        busiInvoiceHeadService.deleteLogic(id);
        return new Result();
    }

    @GetMapping("setDefault")
    @ApiOperation("设置默认发票")
    @Login
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "id", value = "发票抬头id"),
            @ApiImplicitParam(required = true, name = "status", value = "0 是 1 否")
            })
    public Result setDefault(@RequestParam Long id,@RequestParam Integer status) {
        if(1 == status) {
            throw new CustomException("不允许设置成非默认发票抬头！");
        }
        //修改原默认发票为非默认
        busiInvoiceHeadService.updateOldDefault();
        BusiInvoiceHeadDTO busiInvoiceHeadDTO = new BusiInvoiceHeadDTO();
        busiInvoiceHeadDTO.setId(id);
        busiInvoiceHeadDTO.setDefaulted(status);
        busiInvoiceHeadService.update(busiInvoiceHeadDTO);
        return new Result();
    }

}
